

/**
 * 通用JSAPI包装
 * @param {String} api jsapi名称
 * @param {Object || Function} options 配置选项或者回调函数
 */
export function __commonWrap(api, options = {}, config = {}){
    //支持连续调用
    let keepCallback = config.keepCallback

    return new Promise((resolve, reject) => {
        ready(() => {
            AlipayJSBridge.call(api, options, res => {

                if(res && res.error && res.error != 0 && res.error != '0'){
                    window.console && console.info && console.info(`[${api}]方法调用异常：`, options, res);
                    reject(res)
                } else {
                    //对于多次回调支持
                    keepCallback && keepCallback(res);
                    resolve(res)
                }
            })
        })
    })
}

/**
 * 监听jsbridge ready事件
 * @param {Function} callback 回调函数
 */
export function ready (callback) {
    if (window.AlipayJSBridge) {
        callback && callback()
    } else {
        document.addEventListener('AlipayJSBridgeReady', callback, false)
    }
}

/**
 * 生成pushWindow所需要的参数
 * @param {number} appId 目标页的appId
 * @param {Object} param 对客户端的设置
 * @param {Object} passData 需传递的页面参数
 */
export function pushWindowParam(appId, param, pagePushParam){

    const dev = process.env.NODE_ENV === 'development'

    const defaultParam = {
        titleBarColor: 16777215,
        showOptionMenu: true,
        showTitleBar: true,
        titleColor: 0,
        defaultBack: 'back_black'
    }

    //识别使用方法
    const method = dev ? 'pushWindow' : (appId ? 'startH5App' : 'pushWindow')

    let startparams = Object.assign(defaultParam, pagePushParam.pushParam || {}, param)
    
    return {
        method,
        obj: Object.assign(
            (dev || !appId) ? {} : { appId: String(appId) },
            //合并 默认配置 conf配置 传参配置
            method == 'startH5App' ? startparams : {param: startparams}
        )
    }
}

/**
 * 构建参数字符串
 * @param {Object} data 数据对象
 * @returns {String} 对象字符串
 */
export function buildParams (data) {
    let paramsArr = []
    data = data || {}
    for(let key in data){
        paramsArr.push(encodeURIComponent(key || '') 
            + '=' + encodeURIComponent(data[key] || ''))
    }
    return paramsArr.join('&')
}

/**
 * 解构查询字符串参数
 * @param {String} querystring 查询字符串
 * @returns {Object} 数据对象
 */
export function parseParams (querystring) {
    let searchArr = (querystring || '').split('&') || []
    let params = {}
    
    searchArr.forEach(keyvalue => {
        let keyPair = keyvalue.split('=') || []
        if(keyPair[0]){
            params[decodeURIComponent(keyPair[0])] = decodeURIComponent(keyPair[1] || '')
        }
    });

    return params
}

/**
 * 全局唯一标示生成
 */
export function uuid() {
    var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
    var uuid = [], i;
    var len = 8, radix = 16;
    for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random()*radix];
    return uuid.join('');
}

/****
 * 把Object里面的number类型转换成string类型
 * @param obj
 * @returns {*}
 */
export function objNum2String (obj) {
    if (!app.tools.__isObject(obj)) return obj;

    for (let key in obj) {
        if (obj.hasOwnProperty(key) && typeof obj[key] === 'number') {
            obj[key] = obj[key] + '';
        } else if (obj.hasOwnProperty(key) && app.tools.__isObject(obj[key])) {
            objNum2String(obj[key]);
        }
    }
    return obj;
}

